import { getToken } from '@/utils/auth';

// 登录页面
const loginPage: string = "/pages/login";

// 页面白名单
const whiteList: string[] = [
    '/pages/login'
]

// 检查地址白名单
function checkWhite(url: string): boolean {
    const path = url.split('?')[0];
    return whiteList.indexOf(path) !== -1;
}

// 页面跳转验证拦截器
const list: string[] = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];

interface NavigateOptions {
    url: string
    [key: string]: any
}

list.forEach(item => {
    uni.addInterceptor(item, {
        invoke(to: NavigateOptions): boolean {
            if (getToken()) {
                if (to.url === loginPage) {
                    uni.reLaunch({ url: "/pages/index/index" });
                }
                return true;
            } else {
                if (checkWhite(to.url)) {
                    return true;
                } else {
                    uni.reLaunch({ url: loginPage });
                    return false;
                }
            }
        },
        fail(err: any): void {
        }
    })
})